package com.game.astd.spirit.image;

import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import javax.imageio.ImageIO;

import org.apache.http.client.ClientProtocolException;

import com.gargoylesoftware.htmlunit.WebClient;
import com.game.astd.spirit.LoggerUtil;
import com.game.astd.spirit.GameUserInfoUtil;
import com.game.astd.spirit.model.UserData;

/**
 * 验证码
 * 
 * @author Administrator
 * 
 */
public class ImageCodeUtil
{
	static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");

	private static WebClient getWebClient(String username)
	{
		UserData u = GameUserInfoUtil.getUser(username);
		if (u != null)
		{
			return u.getClient();
		}

		return null;
	}

	public static String getImageCode(String username)
	{
		try
		{
			WebClient webClient = getWebClient(username);
			InputStream ins = webClient.getPage("http://www.yaowan.com/Plugins/checkcode.php").getWebResponse().getContentAsStream();
			File f2 = new File(username + "_s_" + sdf.format(new Date(System.currentTimeMillis())) + ".jpg");
			createTmpFile(ins, f2);
			File f = pluszy(username,new FileInputStream(f2));
			String svCode = new OCR().recognizeText(new FileInputStream(f), "jpg");
			return svCode;
		} catch (Exception e)
		{
			LoggerUtil.error(e);
		}

		return "";
	}

	/**
	 * 创建临时文件
	 * 
	 * @param ins
	 * @param f2
	 */
	private static void createTmpFile(InputStream ins, File f2)
	{
		try
		{
			BufferedOutputStream f = new BufferedOutputStream(new FileOutputStream(f2));
			int len = -1;
			byte[] b2 = new byte[1024];
			while ((len = ins.read(b2)) != -1)
			{
				f.write(b2, 0, len);
			}
			f.flush();
			f.close();
		} catch (IOException e)
		{
			LoggerUtil.error(e);
		}
	}

	/**
	 * 去除噪音
	 * 
	 * @param ins
	 * @return
	 */
	private static File pluszy(String username,InputStream ins)
	{
		try
		{
			BufferedImage image;
			image = ImageIO.read(ins);
			int width = image.getTileWidth();
			int height = image.getTileHeight();
			Map<Integer, Integer> mapColor = new HashMap<Integer, Integer>();
			for (int i = 0; i < width; i++)
				for (int j = 0; j < height; j++)
				{
					int color = image.getRGB(i, j);
					Integer count = mapColor.get(color);
					if (count == null)
						count = 0;
					count++;
					mapColor.put(color, count);
				}

			List<Map.Entry<Integer, Integer>> list = new ArrayList<Map.Entry<Integer, Integer>>(mapColor.entrySet());
			Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>() {
				@Override
				public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2)
				{
					return o2.getValue() - o1.getValue();
				}

			});
			int intBack = list.get(0).getKey();
			Set<Integer> setColor = new HashSet<Integer>();
			for (int i = 1; i < 5; i++)
			{
				Map.Entry<Integer, Integer> entry = list.get(i);
				setColor.add(entry.getKey());
			}
			for (int i = 0; i < width; i++)
			{
				for (int j = 0; j < height; j++)
				{
					int color = image.getRGB(i, j);
					if (setColor.contains(color))
						continue;
					image.setRGB(i, j, intBack);
				}
			}

			File tarFile =  new File(username + "_t_" + sdf.format(new Date(System.currentTimeMillis())) + ".jpg");
			ImageIO.write(image, "jpg", tarFile);

			return tarFile;

		} catch (IOException e)
		{
			LoggerUtil.error(e);
		}

		return null;
	}
}
